package JDBC.Day10_Spring.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 *  Druid连接池的工具类
 */
public class JDBCUtils {
    //1. 定义成员变量 DataSource
    private static DataSource ds;

    static {
        try {
            //1. 加载配置文件
            Properties prop = new Properties();
            FileReader fr = new FileReader("src\\JDBC\\Day10_Spring\\druid.properties");
            prop.load(fr);
            //2. 获取DataSource
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  获取连接对象
     * @return  返回连接
     * @throws SQLException 抛出异常
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     *  释放资源
     * @param stmt  执行sql的对象
     * @param conn  归还连接对象
     */
    public static void close(Statement stmt, Connection conn) {
        close(null, stmt, conn);
    }

    /**
     *  释放资源
     * @param rs    结果集对象
     * @param stmt  执行sql对象
     * @param conn  归还连接对象
     */
    public static void close(ResultSet rs, Statement stmt, Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     *  获取连接池方法
     * @return  返回连接池
     */
    public static DataSource getDataSource() {
        return ds;
    }

}
